package com.wx.qiqiai.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.wx.qiqiai.cache.AnswerHistory;
import com.wx.qiqiai.util.JsonUtils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * chargpt服务类
 * 
 * @author zhugh
 * @date 2023/04/05 11:15
 **/
@Service
@Slf4j
public class CharGptService {
    @Value("${openapi-key}")
    private String apiKey;

    @Value("${message-length-max}")
    private int messageLengthMax;

    @Autowired
    private AnswerHistory answerHistory;

    @SneakyThrows
    @Async
    public void sendMsg(String context, String fromUser, Map<String, BlockingQueue<String>> answerMap) {
        List<ChatMessage> messages = answerHistory.get(fromUser);
        if (messages.size() == 0) {
            // 给chatGPT定义一个身份，是一个助手
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setRole("system");
            chatMessage.setContent("你是个乐于助人的助手，你的名字叫柒柒。");
            messages.add(chatMessage);
            answerHistory.save(fromUser, chatMessage);
        }

        ChatMessage userMessage = new ChatMessage();
        userMessage.setRole("user");
        userMessage.setContent(context);
        messages.add(userMessage);

        String answer = "";
        try {
            String messageStr = JsonUtils.toJson(messages);
            log.info(messageStr);
            if (messageStr.length() > messageLengthMax) {
                answer = "问题上下文超限，请清理上下文后重新提问。（回复”2“清理上下文）";
            } else {
                answer = sendMsg(messages);

                // 保存上下文
                answerHistory.save(fromUser, userMessage);

                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setRole("user");
                chatMessage.setContent(answer);
                answerHistory.save(fromUser, chatMessage);
            }
        } catch (Throwable e) {
            log.error("请求open-api异常", e);
            answer = "服务器异常，请重新提问！";
        }
        answerMap.get(fromUser).put(answer);
    }

    public String sendMsg(List<ChatMessage> messages) {
        ChatCompletionRequest request =
            ChatCompletionRequest.builder().messages(messages).model("gpt-3.5-turbo").build();
        OpenAiService service = new OpenAiService(apiKey, 30000);

        // chatCompletion 对象就是chatGPT响应的数据了
        ChatCompletionResult chatCompletion = service.createChatCompletion(request);
        log.info(JsonUtils.toJson(chatCompletion));
        return chatCompletion.getChoices().get(0).getMessage().getContent();
    }
}
